//
//  AIHttpManager.m
//  MiaMind
//
//  Created by Vill on 2023/11/24.
//

#import "AIHttpManager.h"
#import "AIAESUtil.h"
#import "UIApplication+Extension.h"

@implementation AIHttpManager

+ (instancetype)manager{
    static AIHttpManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AIHttpManager alloc] init];
    });
    return manager;
}

- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager{
    _sessionManager = sessionManager;
}

-(instancetype)init{
    self = [super init];
    if (self) {
        self.sessionManager = [AFHTTPSessionManager manager];
        self.sessionManager.responseSerializer.acceptableContentTypes = [self.sessionManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
        self.sessionManager.requestSerializer.timeoutInterval = 60;
        self.sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    }
    return self;
}

- (void)requestMethod:(NSString *)method url:(NSString *_Nullable)url parameters:(NSDictionary *_Nullable)parameters successBlock:(Response _Nullable)successBlock failedBlock:(Error _Nullable)failedBlock showHUD:(BOOL)showHUD{
    if (showHUD){
        [AIUIHelperManager exs_showloading];
    }
    NSLog(@"请求url：%@ \n method:%@ \n param:%@  \n header:%@", url,method,parameters,[self configHeader]);
    NSURLSessionDataTask *dataTask = [self.sessionManager dataTaskWithHTTPMethod:method URLString:url parameters:parameters headers:[self configHeader] uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        //        ZJKJLog(@"上传进度：%@，线程：%@",uploadProgress.localizedDescription,[NSThread currentThread]);
    } downloadProgress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [AIUIHelperManager exs_hideLoading];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = responseObject;
            if ([[dic objectForKey:@"success"] boolValue] == YES) {
                if ([responseObject valueForKey:@"data"]){
                    NSString *jsonString = [AIAESUtil aesDecrypt:[responseObject valueForKey:@"data"]];
                    if ([url containsString:api_coinBalance]){
                        if (jsonString.length > 0){
                            successBlock(jsonString);
                        }
                    }else{
                        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
                        NSError *error;
                        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
                        if (error == nil) {
                            successBlock(dic);
    //                        NSLog(@"返回值：%@", dic);
                        }else{
    //                        [SYIToast showText:@"Network Error!"];
                        }
                    }
                }else{
                    successBlock([responseObject objectForKey:@"object"] ?[responseObject objectForKey:@"object"]: responseObject);
                }
            }else{
                NSDictionary *dic = responseObject;
                // 未登录
                if([dic.allKeys containsObject:@"code"] && [dic[@"code"] integerValue] == 1000){
//                    [[NSNotificationCenter defaultCenter] postNotificationName:TokenExpiredNot object:nil];
                }else{
                    failedBlock([NSError errorWithDomain:[dic objectForKey:@"message"] ? [dic objectForKey:@"message"] : @"Data loading failed, please try again later" code:500 userInfo:nil]);
                }
            }
        }else{
            successBlock([responseObject objectForKey:@"object"] ?[responseObject objectForKey:@"object"]: responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [AIUIHelperManager exs_hideLoading];
        if (error) {
            if (error.code == -1001) {
                failedBlock([NSError errorWithDomain: @"Data loading failed, please try again later" code:error.code  userInfo:error.userInfo]);
                return;
            }
            if (error.code == 3840) {
                failedBlock([NSError errorWithDomain: @"Data loading failed, please try again later" code:999  userInfo:error.userInfo]);
                return;
            }
            failedBlock(error);
        }else{
            failedBlock([NSError errorWithDomain:@"Data loading failed, please try again later" code:500 userInfo:nil]);
        }
    }];
    [dataTask resume];
}

- (void)uploadImage:(UIImage *)image url:(NSString *_Nullable)url successBlock:(Response _Nullable)successBlock failedBlock:(Error _Nullable)failedBlock showHUD:(BOOL)showHUD{
    if (showHUD){
        [AIUIHelperManager exs_showloading];
    }
    NSURLSessionDataTask *dataTask =  [self.sessionManager POST:url parameters:nil headers:[self configHeader] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
       //这里可以用作多个图片上传加一个数组就Ok
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg",str];
        //压缩下
        NSData *imageData =UIImageJPEGRepresentation(image, 1.0);
        /*
         *该方法的参数
         1. appendPartWithFileData：要上传的照片[二进制流]
         2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
         3. fileName：要保存在服务器上的文件名
         4. mimeType：上传的文件的类型
         */
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        NSLog(@"序列化%@",formData);
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [AIUIHelperManager exs_hideLoading];
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = responseObject;
            if ([[dic objectForKey:@"success"] boolValue] == YES) {
                if ([responseObject valueForKey:@"data"]){
                    NSString *jsonString = [AIAESUtil aesDecrypt:[responseObject valueForKey:@"data"]];
                    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
                    NSError *error;
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
                    if (error == nil) {
//                        NSLog(@"返回值：%@", dic);
                        successBlock(dic);
                    }else{
//                        [SYIToast showText:@"Network Error!"];
                    }
                }else{
                    successBlock([responseObject objectForKey:@"object"] ?[responseObject objectForKey:@"object"]: responseObject);
                }
            }else{
                failedBlock([NSError errorWithDomain:[dic objectForKey:@"message"] ? [dic objectForKey:@"message"] : @"Data loading failed, please try again later" code:500 userInfo:nil]);
            }
        }else{
            successBlock([responseObject objectForKey:@"object"] ?[responseObject objectForKey:@"object"]: responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [AIUIHelperManager exs_hideLoading];
        if (error) {
            if (error.code == -1001) {
                failedBlock([NSError errorWithDomain: @"Data loading failed, please try again later" code:error.code  userInfo:error.userInfo]);
                return;
            }
            if (error.code == 3840) {
                failedBlock([NSError errorWithDomain: @"Data loading failed, please try again later" code:999  userInfo:error.userInfo]);
                return;
            }
            failedBlock(error);
        }else{
            failedBlock([NSError errorWithDomain:@"Data loading failed, please try again later" code:500 userInfo:nil]);
        }
    }];
    [dataTask resume];
}

// 设置请求头
- (NSDictionary *)configHeader{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSString *currentLanguage = [[NSLocale preferredLanguages] firstObject]; //格式为语言_地区
    if (currentLanguage.length > 0){
        dic[@"lg"] = currentLanguage;
    }else{
        dic[@"lg"] = @"en";
    }
    dic[@"appVersion"] = UIApplication.sharedApplication.appVersion;
    if ([AIUserInfoManager shareManager].userInfo.token.strHasValue){
        dic[@"token"] = [AIUserInfoManager shareManager].userInfo.token;
        NSLog(@"token --- %@",[AIUserInfoManager shareManager].userInfo.token);
    }
    return dic;
}

/**
 取消所有请求
 */
- (void)cancelAllRequest{
    [self.sessionManager invalidateSessionCancelingTasks:YES resetSession:YES];
}

@end
